package com.ycg.biquge.interceptor;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ycg.biquge.common.UserContext;
import com.ycg.biquge.pojo.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author YCG
 * @date 2024-05-02 20:50
 * @description token过滤器
 */
@Order(1)
@Component("tokenInterceptor")
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 过滤预检请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        // 没有token放行
        if (StrUtil.isBlank(token)) return true;
        // 解析token获取id
        String id = (String) StpUtil.getLoginIdByToken(token);
        if (ObjectUtil.isNull(id)) {
            throw new RuntimeException("token非法!");
        }
        // 将id放入User上下文
        User user = new User();
        user.setId(Integer.valueOf(id));
        UserContext.setUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 删除线程本地变量
        UserContext.clear();
    }
}
